//
//  JXHHomeTableViewController.swift
//  JXHSinaWeiBo
//
//  Created by juxiaohui on 16/10/14.
//  Copyright © 2016年 juxiaohui. All rights reserved.
//

import UIKit
import SDWebImage
import MJRefresh

class JXHHomeTableViewController: JXHBaseTableViewController {

    // MARK: - 懒加载属性
    lazy var temps : [JXHStatusModel] = [JXHStatusModel]()
    lazy var statuses : [JXHStatusViewModel] = [JXHStatusViewModel]()
    lazy var titleBtn : JXHTitleButton = JXHTitleButton()
    lazy var popoViewAnimation : JXHpopoverViewAnimation = JXHpopoverViewAnimation.init {[weak self] (presented) in
    }
    lazy var photoBrowserAnimator = JXHPhotoBrowserAnimator()
    lazy var hudLabel : UILabel = UILabel()
            
    // MARK: - 系统回调函数
    override func viewDidLoad() {
        super.viewDidLoad()
        
        visitorView.addRoationAnimation()
        
        if !islogin {
            return
        }
        //设置导航栏的内容
        
        setupNavgayionBar()
        //请求数据
        
//        loadStatus()
        
       // tableView.rowHeight = UITableViewAutomaticDimension
        
        tableView.estimatedRowHeight = 44 //设置估算高度
        
        setupHeaderView()
        setupFooterView()
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidLoad()
        setupNote()
        setupHudLabel()
    }
}

// MARK: - 设置UI界面
extension JXHHomeTableViewController {
    
    func setupNote() {
        let noteName = NSNotification.Name.init(showPhotoBrowserNote)
        NotificationCenter.default.addObserver(self, selector:#selector(JXHHomeTableViewController.showPhotoBrowser(note:)) , name: noteName, object: nil)
    }

    func setupNavgayionBar() {

        navigationItem.leftBarButtonItem = UIBarButtonItem.init(imageName: "navigationbar_friendattention")
        navigationItem.rightBarButtonItem =  UIBarButtonItem.init(imageName: "navigationbar_pop")
        
        //设置titleView
        titleBtn.setTitle("juxiaohui", for: .normal)
        titleBtn.addTarget(self, action:  #selector(self.titleBtnClick(titleBtn:)), for: .touchUpInside)
        navigationItem.titleView = titleBtn
    }
    
    func setupHudLabel() {
        
        navigationController?.navigationBar.insertSubview(hudLabel, at: 0)
        hudLabel.frame = CGRect.init(x: 0, y: 10, width: UIScreen.main.bounds.width, height: 34)
        hudLabel.backgroundColor = UIColor.orange
        hudLabel.textColor = UIColor.white
        hudLabel.font  = UIFont.systemFont(ofSize: 15)
        hudLabel.textAlignment = .center
        hudLabel.isHidden = true
    }
    
    func setupHeaderView() {
        
        let header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(JXHHomeTableViewController.loadNewStatus))
        tableView.mj_header = header
        
        tableView.mj_header.beginRefreshing()
    }
    
    func setupFooterView() {
        
        let footer = MJRefreshAutoFooter.init(refreshingTarget: self, refreshingAction: #selector(JXHHomeTableViewController.loadMoreStatus))
        tableView.mj_footer = footer
    }
    
    func showHudLabel(count : Int) {
     
        hudLabel.isHidden = false
        hudLabel.text = count == 0 ? "没有新微博" : "更新了\(count)条微博"
        
        UIView.animate(withDuration: 1.0, animations: { 
            
            self.hudLabel.transform = CGAffineTransform.init(translationX: 0, y: 34)
            }) { (_) in
            UIView.animate(withDuration: 1.0, delay: 1.5, options: [], animations: {
                self.hudLabel.transform = CGAffineTransform.identity
                }, completion: { (_) in
                    self.hudLabel.isHidden = true
            })
        }
    }
}

// MARK: - 事件监听
extension JXHHomeTableViewController {
    
    func titleBtnClick(titleBtn : JXHTitleButton){
        
        //改变按钮的状态
        titleBtn.isSelected = !titleBtn.isSelected
        
        let popoverVc = JXHPopoverViewController()
        
        popoverVc.modalPresentationStyle = .custom//(设置这个属性，保证其他控制器不被移除)
        
        //自定义转场动画
        //1.设置转场的代理
        popoverVc.transitioningDelegate = popoViewAnimation
        
        popoViewAnimation.presentFrame = CGRect.init(x: 100, y: 55, width: 180, height: 250)
        
        //当modle 一个控制器时，其他控制器全被移除
        present(popoverVc, animated: true, completion: nil)
        
    }
    
    func showPhotoBrowser(note : NSNotification)  {
        
        let indexPath = note.userInfo!["indexPath"] as! NSIndexPath
        let picURLs = note.userInfo!["picURLs"] as! [URL]
        
        let object = note.object as! JXHCustomCollectionView
        
        let photoBrowserVc = JXHPhotoBrowserController.init(indexPath: indexPath, picURLs: picURLs)
        photoBrowserVc.transitioningDelegate = photoBrowserAnimator
        
        photoBrowserAnimator.presentDelegate = object
        
        photoBrowserAnimator.indePath = indexPath as IndexPath
        
        photoBrowserAnimator.dissmissDelegate = photoBrowserVc
        
        photoBrowserVc.modalPresentationStyle = .custom
        
        present(photoBrowserVc, animated: true, completion: nil)
    }
    
}

// MARK: - 请求数据相关
extension JXHHomeTableViewController {

    func loadNewStatus()  {
        
        loadStatus(isNewData: true)
    }
    
    func loadMoreStatus()  {
        
        loadStatus(isNewData: false)
    }
    
    
    func loadStatus(isNewData : Bool)  {
        
        var since_id = 0
        var max_id = 0
        
        if isNewData {
            since_id = statuses.first?.status?.mid ?? 0
        }else{
            max_id = statuses.last?.status?.mid ?? 0
            
            max_id = max_id == 0 ? 0 : (max_id - 1)
        }

        JXHNetWorkTools.shareInstance.loadStatus(since_id: since_id, max_id: max_id){(resultArray, error) in
            
            if error != nil {
                return
            }
            
            guard let resultArray = resultArray else {
                return
            }
            
            var tempStatuses = [JXHStatusViewModel]()
            
            for statusDic in resultArray {
                let statu = JXHStatusModel.init(dic: statusDic)
                let viewModel = JXHStatusViewModel.init(status: statu)
                tempStatuses.append(viewModel)
            }
            
            if isNewData {
                self.statuses = tempStatuses + self.statuses
            }else{
                self.statuses += tempStatuses
        
            }
            
            /// 缓存图片
            self.cacheImages(viewModels: tempStatuses, isNewData: isNewData)
        }
    }
    
    func cacheImages(viewModels : [JXHStatusViewModel],isNewData : Bool) {
        
        let group : DispatchGroup = DispatchGroup.init()
        
        for viewModel in viewModels {
            for picURL in viewModel.picURLs {
                group.enter()
                SDWebImageManager.shared().downloadImage(with: picURL, options: [], progress: nil, completed: { (_, _, _, _, _) in
                 group.leave()
                })
            }
        }
        
        group.notify(queue: .main) {
            self.tableView.reloadData()
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            if isNewData {
                self.showHudLabel(count: viewModels.count)
            }
        }
    }
}


// MARK: - TableView数据源方法
extension JXHHomeTableViewController {
    
    override func numberOfSections(in tableView: UITableView) -> Int {
      
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  
        return statuses.count
    }
    
  
     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell")! as! JXHHomeCell
        
        let viewModel = statuses[indexPath.row]
        
        cell.viewModel = viewModel
        
        return cell
     }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return statuses[indexPath.row].cellHeght
    }
}



